<script setup lang="ts">
import { ref } from 'vue';
import { RouterView } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import SiderMenu from '@/components/SiderMenu.vue';
import { useRouter, useRoute } from 'vue-router';
import CisdiLogo from '@/assets/images/cisdi-logo.png';

const openSidebar = ref<boolean>(
  localStorage.getItem('openSidebar') === 'true' && import.meta.env.MODE !== 'production'
);
// 在开发环境下，可以通过Ctrl+B来控制侧边栏的显示与隐藏
if (import.meta.env.MODE !== 'production') {
  document.addEventListener('keydown', function (event) {
    if (event.ctrlKey && event.key === 'b') {
      openSidebar.value = !openSidebar.value;
      localStorage.setItem('openSidebar', String(openSidebar.value));
    }
  });
}

const menuList = useRouter().options.routes as RouteRecordRaw[];
const route = useRoute();

const getQueryData = () => {
  const params = new URLSearchParams(window.location.search);
  const token = params.get('token');
  return token ? token : null;
};
// 在生产环境下，通过url中的token来设置localStorage中的token
if (import.meta.env.MODE === 'production') {
  const token = getQueryData();
  if (token) {
    localStorage.setItem('token', token);
  }
}
</script>

<template>
  <div class="flex h-full">
    <!-- 通过在localStorage中设置openSidebar的值来控制侧边栏的显示与隐藏 -->
    <aside class="flex flex-col w-[260px] bg-[#20243b]" v-if="openSidebar">
      <div>
        <div
          class="flex items-center box-border bg-[#2f3757] border-b-[#45495b] shadow-inner-y h-[60px] pl-[30px] text-xl text-[#eee]"
        >
          <img :src="CisdiLogo" class="h-5 mr-1" />标准化项目
        </div>
      </div>
      <div class="text-center text-green-400 select-none">按下Ctrl+B隐藏/显示侧边栏</div>
      <el-menu
        class="overflow-y-auto !border-0"
        background-color="#20243b"
        text-color="#c3c3c3"
        :default-active="route.path"
        unique-opened
        router
      >
        <SiderMenu :menuList="menuList" />
      </el-menu>
    </aside>
    <!-- 当freeScreen设为true时，一般用于像一张图这样需要任意拖动，而不被滚动条限制的页面 -->
    <router-view v-if="route.meta.freeScreen" class="flex-1" />
    <!-- 经过容器限制的页面，适用于普通业务表单页面 -->
    <div v-else class="relative flex-1 h-full overflow-y-auto">
      <router-view />
    </div>
  </div>
</template>

<style scoped lang="scss">
.el-menu::-webkit-scrollbar {
  width: 8px;
}
.el-menu::-webkit-scrollbar-thumb {
  background-color: #45495b;
  border-radius: 4px;
}
.el-menu {
  :deep(.el-menu-item.is-active) {
    --el-menu-active-color: #fff;
    background-color: #3f4b99;
  }
}
</style>
